package com.ns.dcjh.ui.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupAnimation;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.ns.dcjh.R;
import com.ns.dcjh.base.BaseActivity;
import com.ns.dcjh.bean.FullScreen;
import com.ns.dcjh.bean.MessageEvent;
import com.ns.dcjh.constant.Constant;
import com.ns.dcjh.enums.TextColorEnum;
import com.ns.dcjh.ui.popup.FullScreenSettingPopup;
import com.ns.dcjh.ui.popup.OnFullScreenPopupChangeListener;
import com.ns.dcjh.ui.widget.MyScrollLinearLayout;
import com.ns.dcjh.ui.widget.OnScrollCompleteListener;
import com.ns.dcjh.utils.FileUtils;
import com.ns.dcjh.utils.SharedPreferencesUtils;
import com.ns.dcjh.utils.StatusBarUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;

public class FullScreenActivity extends BaseActivity {

    @BindView(R.id.rootView)
    RelativeLayout rootView;

    @BindView(R.id.fullScreenContentRoot)
    MyScrollLinearLayout fullScreenContentRoot;
    @BindView(R.id.displayContent)
    TextView displayContent;

    @BindView(R.id.statusBarRoot)
    LinearLayout statusBarRoot;
    @BindView(R.id.btnRoot)
    RelativeLayout btnRoot;
    @BindView(R.id.btnBack)
    ImageView btnBack;
    @BindView(R.id.btnSetting)
    ImageView btnSetting;
    @BindView(R.id.btnRefresh)
    ImageView btnRefresh;

    @BindView(R.id.fullScreenFinishScrollTxt)
    TextView fullScreenFinishScrollTxt;
    @BindView(R.id.fullScreenImagePlay)
    ImageView fullScreenImagePlay;

    @BindView(R.id.fullScreenCutDownRoot)
    RelativeLayout fullScreenCutDownRoot;
    @BindView(R.id.displayCutDownText)
    TextView displayCutDownText;

    private boolean isLandscape = false;

    private GestureDetector detector = null;

    private boolean isBackgroundBack = true; //默认黑色背景

    private int defaultTextColorRes = R.color.white;

    private FullScreenSettingPopup settingPopup;

    private FullScreen fullScreen = new FullScreen();

    //Y轴手势移动的距离
    private int gestureHeight = 0;
    //Y轴运动的距离
    private int pauseDyHeight = 0;

    private int gestureType = -1; // 0代表单击 1代表滑动

    //提词器内容高度
    private int contentTextHeight = 0;
    int screenHeight = 0;

    private int cutDownTime = 2; //默认倒计时时间
    private CountDownTimer countDownTimer;

    private float textSize = 35f;
    private int textColorType = 1011; //字体颜色类型
    private boolean isTextMirror = false; //是否镜像
    private final int speedFactor = 20;
    //    private float speed = 2 / (4 + 0.4f * speedFactor); //默认速度2
    private float speed = 1.8f / speedFactor; //默认速度


    private boolean isScrollFinish = false;

    private boolean isScrollPause = false;

    private SharedPreferencesUtils spUtil;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_full_screen;
    }


    protected void initStatusBar() {
        StatusBarUtils.setTranslucentStatusAndDark(mContext);
    }


    @Override
    protected void initData() {
        spUtil = SharedPreferencesUtils.getInstance(this);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
//        int screenWidth = dm.widthPixels;
        if (getIntent().getIntExtra("orientation", 0) == 0) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
            screenHeight = dm.heightPixels;
            Log.e("TAG", "屏幕高为" + screenHeight);
            isLandscape=false;
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            screenHeight = dm.widthPixels;
            Log.e("TAG", "屏幕高为" + screenHeight);
            isLandscape=true;
        }
        //读取初始设置值
        getDefaultSettingValue();


    }

    private void getDefaultSettingValue() {
        String jsonStr;
        if (isLandscape){
            if (spUtil.contain("fullSetting_hor")) {
                jsonStr = (String) spUtil.objectForKey("fullSetting_hor", "");
            } else {
                jsonStr = FileUtils.getAssetsJson("fullScreen_hor.json", this);
            }
        }else {
            if (spUtil.contain("fullSetting")) {
                jsonStr = (String) spUtil.objectForKey("fullSetting", "");
            } else {
                jsonStr = FileUtils.getAssetsJson("fullScreen.json", this);
            }
        }

        fullScreen = new Gson().fromJson(jsonStr, FullScreen.class);
        cutDownTime = fullScreen.cutDownTime;
        textSize = fullScreen.textSize;
        textColorType = fullScreen.textColorType;
        speed = fullScreen.speed / speedFactor;
        isBackgroundBack = fullScreen.background == 1001;
        isTextMirror = fullScreen.isTextMirror == 1;
    }


    @Override
    protected void initView() {
        setStatusBarHeight();

        initPopup();

        initDefaultBackgroundUi();

        detector = new GestureDetector(this, listener);

        btnRoot.setVisibility(View.GONE);
        fullScreenContentRoot.setVisibility(View.INVISIBLE);

        fullScreenContentRoot.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    if (gestureType == 1) {
                        int startPoint = pauseDyHeight + gestureHeight;
                        int dy = (int) (0.7 * screenHeight) + contentTextHeight + 200 - startPoint;
                        fullScreenContentRoot.startScroll(dy, startPoint, speed);
                    }
                }
                return detector.onTouchEvent(motionEvent);
            }
        });


        if (isBackgroundBack) {
            fullScreenCutDownRoot.setBackgroundResource(R.color.black);
            displayCutDownText.setTextColor(getResources().getColor(R.color.white));
        } else {
            fullScreenCutDownRoot.setBackgroundResource(R.color.white);
            displayCutDownText.setTextColor(getResources().getColor(R.color.black));
        }
        initCutDownTime();


        fullScreenContentRoot.setContentTopDistance((int) (screenHeight * 0.7));


        displayContent.setTextColor(getResources().getColor(TextColorEnum.getColorByType(textColorType)));
        displayContent.setText(getIntent().getStringExtra("content"));
        displayContent.setTextSize(textSize);

        if (isTextMirror) {
            displayContent.setScaleX(-1);
        } else {
            displayContent.setScaleX(1);
        }

        displayContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (displayContent != null) {
                    int width = displayContent.getWidth();
                    int height = displayContent.getHeight();
                    Log.e("TAG", "长宽分别为(" + width + "," + height + ")");
//                    contentTextHeight = displayContent.getHeight();


                    contentTextHeight = displayContent.getLayout().getHeight()  //  文字的高度
                            + displayContent.getPaddingTop()
                            + displayContent.getPaddingBottom();
                    Log.e("TAG", "contentHeight=" + contentTextHeight);

                }
            }
        });

        fullScreenContentRoot.setOnScrollCompleteListener(new OnScrollCompleteListener() {
            @Override
            public void onScrollComplete(int dy) {
                if (dy < (int) (0.7 * screenHeight) + contentTextHeight + 200) {
                    pauseDyHeight = dy;
                } else {
                    isScrollFinish = true;
                    isScrollPause = false;
                    fullScreenFinishScrollTxt.bringToFront();
                    fullScreenFinishScrollTxt.setVisibility(View.VISIBLE);

                }

            }
        });


        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        btnSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!settingPopup.isShow()) {
                    settingPopup.show();
                }
            }
        });

        btnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isScrollFinish = false;
                isScrollPause = false;
                fullScreenImagePlay.setVisibility(View.GONE);
                fullScreenFinishScrollTxt.setVisibility(View.GONE);
//                rootView.removeView(fullScreenContentRoot);
//                fullScreenContentRoot = null;
//                displayContent = null;

                initDefaultBackgroundUi();
                setSettingContent();

                if (cutDownTime != 0) { //直接开始移动
                    btnRoot.setVisibility(View.GONE);
                    fullScreenContentRoot.setVisibility(View.INVISIBLE);
                    initCutDownTime();
                }

                startContentScroll();

            }
        });

        fullScreenFinishScrollTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { //重新播放
                fullScreenFinishScrollTxt.setVisibility(View.GONE);
                startContentScroll();
                isScrollFinish = false;
            }
        });
    }

    private void setStatusBarHeight() {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) statusBarRoot.getLayoutParams();
        params.height = StatusBarUtils.getStatusBarHeight(this);
        statusBarRoot.setLayoutParams(params);
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void dataRequest() {

    }

    /**
     * 根据设置数据重设TextView
     */
    private void setSettingContent() {
        fullScreenContentRoot.setContentTopDistance((int) (0.7 * screenHeight));

        displayContent.setText(getIntent().getStringExtra("content"));
        displayContent.setTextColor(getResources().getColor(TextColorEnum.getColorByType(textColorType)));
        displayContent.setTextSize(textSize);
        if (isTextMirror) {
            displayContent.setScaleX(-1);
        } else {
            displayContent.setScaleX(1);
        }
    }


    //设置背景UI
    private void initDefaultBackgroundUi() {
        fullScreenContentRoot.setBackgroundResource(isBackgroundBack ? R.color.black : R.color.white);
        btnBack.setBackgroundResource(isBackgroundBack ? R.mipmap.ic_back_white : R.mipmap.ic_back_black);
        btnSetting.setBackgroundResource(isBackgroundBack ? R.mipmap.ic_setting_white : R.mipmap.ic_setting_black);
        btnRefresh.setBackgroundResource(isBackgroundBack ? R.mipmap.ic_refresh_white : R.mipmap.ic_refresh_black);
        fullScreenFinishScrollTxt.setTextColor(getResources().getColor(isBackgroundBack ? R.color.white : R.color.black));
        fullScreenImagePlay.setBackgroundResource(isBackgroundBack ? R.mipmap.ic_paly_white : R.mipmap.ic_play_black);
    }

    private void initPopup() {
        settingPopup = (FullScreenSettingPopup) new XPopup.Builder(this)
                .atView(btnRoot)
                .hasShadowBg(false)
                .popupAnimation(PopupAnimation.NoAnimation)
                .setPopupCallback(new SimpleCallback() {

                    @Override
                    public void onShow(BasePopupView popupView) {
                        super.onShow(popupView);
                        Log.e("TAG", "onShow");
                        statusBarRoot.setBackgroundResource(R.color.color_background_popup);
                        btnRoot.setBackgroundResource(R.color.color_background_popup);
                        if (!isBackgroundBack) {
                            btnBack.setBackgroundResource(R.mipmap.ic_back_white);
                            btnSetting.setBackgroundResource(R.mipmap.ic_setting_white);
                            btnRefresh.setBackgroundResource(R.mipmap.ic_refresh_white);
                        }

                        fullScreenContentRoot.stopScroll();


                        fullScreenImagePlay.setVisibility(View.GONE);


                    }

                    @Override
                    public void onDismiss(BasePopupView popupView) {
                        super.onDismiss(popupView);
                        statusBarRoot.setBackgroundResource(R.color.transparent_white);
                        btnRoot.setBackgroundResource(R.color.transparent_white);
                        if (!isBackgroundBack) {
                            btnBack.setBackgroundResource(R.mipmap.ic_back_black);
                            btnSetting.setBackgroundResource(R.mipmap.ic_setting_black);
                            btnRefresh.setBackgroundResource(R.mipmap.ic_refresh_black);
                        }

                        fullScreenContentRoot.startScroll((int) (0.7 * screenHeight) + contentTextHeight + 200 - pauseDyHeight, pauseDyHeight, speed);
                        if (isScrollPause) {
                            isScrollPause = false;
                        }
                    }
                })
                .asCustom(new FullScreenSettingPopup(this, fullScreen,isLandscape));


        settingPopup.setOnFullScreenPopupChangeListener(new OnFullScreenPopupChangeListener() {
            @Override
            public void onChangeBackgroundColor(int colorType) { //更改背景颜色
                if (colorType == FullScreenSettingPopup.BACKGROUND_BLACK) {
                    isBackgroundBack = true;
                    initDefaultBackgroundUi();

                    fullScreenCutDownRoot.setBackgroundResource(R.color.black);
                    displayCutDownText.setTextColor(getResources().getColor(R.color.white));

                } else if (colorType == FullScreenSettingPopup.BACKGROUND_WHITE) {
                    isBackgroundBack = false;
                    fullScreenContentRoot.setBackgroundResource(isBackgroundBack ? R.color.black : R.color.white);

                    fullScreenCutDownRoot.setBackgroundResource(R.color.white);
                    displayCutDownText.setTextColor(getResources().getColor(R.color.black));

                    fullScreenFinishScrollTxt.setTextColor(getResources().getColor(R.color.black));
                    fullScreenImagePlay.setBackgroundResource(R.mipmap.ic_play_black);

                }
                fullScreen.background = colorType;
                saveSettings();

            }

            @Override
            public void onChangeTextColor(int colorType) {
                textColorType = colorType;
                displayContent.setTextColor(getResources().getColor(TextColorEnum.getColorByType(colorType)));
                fullScreen.textColorType = colorType;
                saveSettings();
            }

            @Override
            public void onChangeTextSize(int size) {
                textSize = size;
                displayContent.setTextSize((float) size);
                fullScreen.textSize = size;
                saveSettings();
            }

            @Override
            public void onChangeSwitchReverseText(boolean isOn) {
                Log.e("TAG", isOn + "");
                isTextMirror = isOn;
                if (isOn) {
                    displayContent.setScaleX(-1);
                } else {
                    displayContent.setScaleX(1);
                }
                fullScreen.isTextMirror = isOn ? 1 : 0;
                saveSettings();
            }

            @Override
            public void onChangeCutDownTime(int time) {
                cutDownTime = time;
                fullScreen.cutDownTime = time;
                saveSettings();
            }

            @Override
            public void onChangeSpeed(float speedValue) {
                speed = speedValue / speedFactor;
                fullScreen.speed = speedValue;
                saveSettings();
            }

            @Override
            public void onCompleteClick() {
            }

            @Override
            public void onRecover() {
                if (isLandscape){
                    spUtil.removeObjectForKey("fullSetting_hor");
                    fullScreen = new Gson().fromJson(FileUtils.getAssetsJson("fullScreen_hor.json", FullScreenActivity.this), FullScreen.class);
                }else {
                    spUtil.removeObjectForKey("fullSetting");
                    fullScreen = new Gson().fromJson(FileUtils.getAssetsJson("fullScreen.json", FullScreenActivity.this), FullScreen.class);
                }
                saveSettings();



            }
        });
    }

    private void saveSettings() {
        String jsonStr = new Gson().toJson(fullScreen);
        if (isLandscape){
            spUtil.setObject("fullSetting_hor", jsonStr);
        }else {
            spUtil.setObject("fullSetting", jsonStr);
        }
    }

    private void initCutDownTime() {
        fullScreenCutDownRoot.setVisibility(View.VISIBLE);
        displayCutDownText.setText(String.valueOf(cutDownTime));
        countDownTimer = new CountDownTimer(cutDownTime * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                String value = String.valueOf((int) (millisUntilFinished / 1000));
                displayCutDownText.setText(value);
            }

            @Override
            public void onFinish() { //倒计时结束
                fullScreenCutDownRoot.setVisibility(View.GONE);
                fullScreenContentRoot.setVisibility(View.VISIBLE);
                btnRoot.setVisibility(View.VISIBLE);

                startContentScroll();

                countDownTimer.cancel();
                countDownTimer = null;
            }
        };

        countDownTimer.start();
    }

    private void startContentScroll() {
        int dy = (int) (0.7 * screenHeight) + contentTextHeight + 200;
        Log.e("TAG", "0.7*screenHeight==" + 0.7 * screenHeight);
        Log.e("TAG", "initView: " + "移动量：" + dy);

        fullScreenContentRoot.startScroll(dy, 0, speed);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }

        MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_PROMPT_EXIT);
        EventBus.getDefault().post(msgEvent);
    }

    GestureDetector.SimpleOnGestureListener listener = new GestureDetector.SimpleOnGestureListener() {

        private int y;

        @Override
        public boolean onDown(MotionEvent e) {
            Log.e("TAG", "触碰了");
            //记录手指触碰初始位置
            y = (int) e.getY();

            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            gestureType = 0;
            if (isScrollFinish) {
                fullScreenFinishScrollTxt.setVisibility(View.GONE);
                startContentScroll();
                isScrollFinish = false;
            } else {
                if (isScrollPause) {
                    fullScreenImagePlay.setVisibility(View.GONE);
                    fullScreenContentRoot.startScroll((int) (0.7 * screenHeight) + contentTextHeight + 200 - pauseDyHeight, pauseDyHeight, speed);
                } else {
                    fullScreenContentRoot.stopScroll();
                    fullScreenImagePlay.bringToFront();
                    fullScreenImagePlay.setVisibility(View.VISIBLE);
                }
                isScrollPause = !isScrollPause;
            }
            return super.onSingleTapUp(e);
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            gestureType = 1;
            int startY = (int) e1.getY();
            int endY = (int) e2.getY();
            fullScreenContentRoot.stopScroll();

            int offsetY = endY - y;

            fullScreenContentRoot.scrollBy(0, -offsetY);

            y = endY;

            gestureHeight = startY - endY;

            if (gestureHeight < 0 && gestureHeight < ((int) (0.3 * screenHeight) + pauseDyHeight + 200) * -1) { //向下滑出屏幕
                gestureType = -1;

                isScrollFinish = true;
                isScrollPause = false;
                fullScreenFinishScrollTxt.bringToFront();
                fullScreenFinishScrollTxt.setVisibility(View.VISIBLE);
            }

            return true;
        }
    };

}